package com.bravo.friend.filter;

import com.bravo.common.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author: Yuyong
 * @create: 2019-08-29 11:28
 **/

@Component
@Slf4j
public class JwtFilter extends HandlerInterceptorAdapter {

    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("经过了拦截器");
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            String token = authHeader.substring(7);
            Claims claim = jwtUtil.parseJWT(token);
            if (claim != null) {
                //如果是管理员
                if ("admin".equals(claim.get("roles"))){
                    request.setAttribute("admin_claim",claim);
                }
                //如果是用户
                if ("user".equals(claim.get("roles"))){
                    request.setAttribute("user_claim",claim);
                }
            }
        }
        return true;
    }
}
